// const baseurl = 'http://192.168.4.1'
// const baseurl = window.location.origin
console.log(baseurl)
const CONSTANT = {
  wlanName: '',
  GET_BASE_URL: `${baseurl}/wlan_general`,
  GET_HIGH_URL: `${baseurl}/wlan_advance`,
}

// var Ajax = {
//   get: function(url,callback){
//     // XMLHttpRequest对象用于在后台与服务器交换数据
//     console.log('456789')
//     var xhr=new XMLHttpRequest();
//     xhr.open('GET', url,true);
//     xhr.setRequestHeader('Content-Type','application/json');
//     xhr.onreadystatechange=function(){
//       if(xhr.readyState === 4){
//         if(xhr.status === 200 || xhr.status === 304){
//           console.log(xhr.responseText);
//           callback(xhr.responseText);
//         } else {
//           console.log(xhr.responseText);
//         }
//       }
//     }
//     xhr.send();
//   },
//   put: function(url, data, callback) {
//     var xhr=new XMLHttpRequest();
//     xhr.open('put', url,true);
//     xhr.setRequestHeader('Content-Type','application/json');
//     xhr.onreadystatechange=function(){
//       if(xhr.readyState === 4){
//         if(xhr.status === 200 || xhr.status === 304){
//           console.log(xhr.responseText);
//           callback(xhr.responseText);
//         } else {
//           console.log(xhr.responseText);
//         }
//       }
//     }
//     xhr.send(JSON.stringify(data));
//   },
//   post: function(url, data, callback){
//     var xhr=new XMLHttpRequest();
//     xhr.open('POST', url,true);
//     // 添加http头，发送信息至服务器时内容编码类型
//     xhr.setRequestHeader('Content-Type','application/json');
//     xhr.onreadystatechange=function(){
//       console.log('1: ', xhr.readyState)
//       console.log('2: ', xhr.status)
//       console.log('3: ', xhr.responseText)
//       if (xhr.readyState === 4){
//         if (xhr.status === 200 || xhr.status === 304){
//           callback(xhr.responseText);
//         }
//       }
//     }
//     xhr.send(JSON.stringify(data));
//   }
// }

// function baseSetting() {
//   var baseArray1 = document.getElementsByClassName('header-title-one')
//   var base1 = baseArray1[0]
//   base1.style.color = '#000'
//   base1.style.cursor = 'auto'
//   var baseArray = document.getElementsByClassName('header-title-two')
//   var base = baseArray[0]
//   base.style.color = '#888888'
//   base.style.cursor = 'pointer'
//   var baseShow = document.getElementById('baseShow')
//   baseShow.style.display = 'block'
//   var highShow = document.getElementById('highShow')
//   highShow.style.display = 'none'
// }

// function advanceSetting() {
//   console.log('点击高级设置')
//   var base1 = document.querySelector('.header-title-one')
//   base1.style.color = '#888888'
//   base1.style.cursor = 'pointer'
//   var base = document.querySelector('.header-title-two')
//   base.style.color = '#000'
//   base.style.cursor = 'auto'
//   var baseShow = document.getElementById('baseShow')
//   baseShow.style.display = 'none'
//   var highShow = document.getElementById('highShow')
//   highShow.style.display = 'block'
// }

function baseSave() {
  var wlanName = document.getElementById('wlanName')
  console.log('wlan 名称：', wlanName.value)
  var model = document.getElementById('model')
  console.log('安全模式：', model.value)
  var password = document.getElementById('password')
  console.log('密码：', password.value)
  var select = document.getElementById('select')
  console.log('wlan 隐身：', select.checked)
  var isSelect = 'false'
  if (select.checked) {
    isSelect = 'true'
  }
  Ajax.post(CONSTANT.GET_BASE_URL, {ssid: wlanName.value, if_hide_ssid: isSelect, auth_mode: model.value, password: password.value}, function (res) {
    console.log('基本信息保存：', res)
  })
}

function highSave() {
  var broadband = document.getElementById('broadband')
  console.log('宽带：', broadband.value)
  var channel = document.getElementById('channel')
  console.log('信道：', channel.value)
  Ajax.post(CONSTANT.GET_HIGH_URL, {bandwidth: broadband.value, channel: channel.value}, function (res) {
    console.log('高级信息保存：', res)
  })
}

var isMobile=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||768)<=768;
window.onresize=function(){isMobile=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||768)<=768};

function getaprecord() {
//   showLoading();
  console.log("getaprecord");
  Ajax.get("/getaprecord", function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
          if (c.state == 0) {
              wifiList = c.aplist;
              initWifiList(wifiList, null);
            //   hideLoading("msg-load")
          } else {
              alert("getWifiFailed")
          }
      } catch (d) {
        alert("getWifiFailed")
      }
  })
}

function initWifiList(x, r) {
  removeWifiList();
  var s = document.createElement("div");
  s.setAttribute("id", "wifi-list-wrap");
  s.setAttribute("class", "wifi-list-wrap");
  if (isMobile) {
      var q = document.createElement("div");
      q.setAttribute("class", "mask");
      q.setAttribute("id", "mask");
      q.onclick = function() {
          removeWifiList()
      };
      s.appendChild(q)
  }
  var y = document.createElement("ul");
  var v = "";
  var t = document.getElementById("sta-ssid")
      .value;
  console.log(t);
  for (var u = 0; u < x.length; u++) {
      var p = x[u];
      if (r && p.ssid.indexOf(r) == -1) {
          continue
      }
      var z = "";
      if (t == p.ssid) {
          z = "active"
      }
      v += '<li data-value="' + p.ssid +
          '" onclick="selectCurWifi(event)" class="d-flex d-a-i ' +
          z + '"><span class="selected"></span>' + p.ssid;
      if (p.auth_mode && p.auth_mode != 0) {
          v += '<span class="lock-img"><svg class="icon" width="12px" height="12px" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M800.421 436.525H736.76V287.852c0-124.507-100.762-225.757-224.732-225.757-123.98 0-224.857 101.25-224.857 225.766v148.662h-63.593c-30.667 0-55.532 24.952-55.532 55.752v407.048c0 30.848 24.865 55.82 55.532 55.82h576.9c30.667 0 55.465-24.97 55.465-55.82V492.275c0-30.802-24.855-55.752-55.532-55.752zM543.203 706.409v88.88a7.354 7.354 0 0 1-7.282 7.325h-47.733a7.373 7.373 0 0 1-7.334-7.322V706.41c-22.423-11.518-37.953-34.602-37.953-61.659 0-38.288 30.945-69.425 69.07-69.425 38.183 0 69.138 31.136 69.138 69.415 0.057 27.067-15.473 50.152-37.905 61.659z m107.311-269.884H373.525V291.539c0-76.691 62.196-139.146 138.552-139.146 76.366 0 138.447 62.454 138.447 139.146v144.986z" fill="#666666" ></path></svg></span>'
      }
      v += "</li>"
  }
  if (v == "") {
      v = '<li class="no-data">' + getPrompt("noData") + "</li>"
  }
  y.innerHTML = v;
  if (isMobile) {
      var w = document.createElement("div");
      w.setAttribute("class", "content");
      var n = document.createElement("div");
      n.innerHTML = "<h3>" + getPrompt("wifiList") +
          '<span onclick="getaprecord()" id="refresh" class="refresh">' +
          getPrompt("refresh") + "</span></h3>";
      var o = document.createElement("div");
      o.setAttribute("class", "cancel-wrap");
      o.setAttribute("id", "cancel-wrap");
      o.innerHTML = getPrompt("cancel");
      o.onclick = function() {
          removeWifiList()
      };
      w.appendChild(n);
      w.appendChild(y);
      w.appendChild(o);
      s.appendChild(w);
      document.getElementById("body-wrap")
          .appendChild(s);
      return
  }
  s.appendChild(y);
  document.getElementById("ssid-wrap")
      .appendChild(s)
}

function selectCurWifi(b) {
  console.log(b.target.dataset.value);
  isShowWifi = false;
  document.getElementById("sta-ssid")
      .value = b.target.dataset.value;
  removeWifiList()
}

function initShowList() {
  document.getElementById("show-wifi-list")
      .onclick = function(b) {
          console.log(isShowWifi);
          isShowWifi = !isShowWifi;
          console.log(isShowWifi);
          if (isShowWifi) {
              getaprecord()
          } else {
              removeWifiList()
          }
          document.getElementById("sta-ssid")
              .focus();
          window.event ? window.event.cancelBubble = true : b
              .stopPropagation()
      };
  document.getElementById("sta-ssid")
      .onclick = function(b) {
          window.event ? window.event.cancelBubble = true : b
              .stopPropagation()
      };
  document.getElementById("body-wrap")
      .onclick = function(b) {
          if (!isMobile) {
              isShowWifi = false;
              removeWifiList()
          }
      };
  document.getElementById("sta-ssid")
      .oninput = function() {
          console.log("oninput");
          console.log(isShowWifi);
          console.log(isMobile);
          if (isShowWifi && !isMobile) {
              var b = document.getElementById("wifi-list-wrap");
              console.log(b);
              if (b) {
                  console.log(this.value);
                  document.getElementById("ssid-wrap")
                      .removeChild(b);
                  initWifiList(wifiList, this.value)
              }
          }
      }
}

function removeWifiList() {
  if (isMobile) {
      isShowWifi = false
  }
  var b = document.getElementById("wifi-list-wrap");
  if (b) {
      document.getElementById(isMobile ? "body-wrap" :
              "ssid-wrap")
          .removeChild(b);
      b = document.getElementById("wifi-list-wrap");
      if (b) {
          removeWifiList()
      }
  }
}

function getData() {
  Ajax.get("/getstainfo", function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
          document.getElementById("sta-ssid")
              .value = c.sta_ssid;
          document.getElementById("sta-password")
              .value = c.sta_password;
          document.getElementById("sta-message")
              .value = c.message
      } catch (d) {}
  })
}

function getStatus() {
  if (timeoutNum > 40) {
      // hideLoading("msg-load");
      // showMessage(getPrompt("connectTimeout"), 2000);
      alert("连接超时")
      return false
  }
  timeoutNum++;
  Ajax.get("/getstainfo", function(b) {
      b = JSON.parse(b);
      console.log(b);
      document.getElementById("sta-message")
          .value = b.message;
      if (b.state == 1) {
        //   getResult()
      } else {
          if (b.state == 0) {
              setTimeout(function() {
                  getStatus()
              }, 1000)
          } else {
              // hideLoading("msg-load");
              // showMessage(getPrompt("connectFailed"),
              //     2000)
              alert("连接失败")
          }
      }
  })
}

// function getResult() {
//   var b = "received=1";
//   Ajax.post("/getresult", b, function(a) {
//       isSend = false;
//       // hideLoading("msg-load");
//       // showTimeout()
//       alert("配置超时")
//   })
// }

function postStaData() {
  timeoutNum = 0;
  var f = document.getElementById("sta-ssid")
      .value;
  var e = document.getElementById("sta-password")
      .value;
  if (f == "" || f == null) {
      // showMessage(getPrompt("enterSsid"), 1000);
      alert("请输入SSID")
      return false
  }
  if (f.length > 32) {
      // showMessage(getPrompt("ssidError"), 1000);
      alert("SSID长度不能超过32个字符")
      return false
  }
  if (e.length > 64) {
      // showMessage(getPrompt("passwordError"), 1000);
      alert("密码长度不能超过64个字符")
      return false
  }
  var d = {"sta_ssid":f, "sta_password":e};
  Ajax.post("/setstainfo", d, function(a) {
      a = JSON.parse(a);
      isSend = true;
      console.log(a);
      if (a.state == 0) {
          setTimeout(function() {
              getStatus()
          }, 1000)
      } else {
          // hideLoading("msg-load");
          // showMessage(getPrompt("connectFailed"), 2000)
          alert("连接失败")
      }
  })
}

function initHash () {
  console.log('页面第一次加载')

  const leftMenuElement = document.getElementById('idLeftMenuWLAN');
  leftMenuElement.classList.add('content');

  selectTitle(document.getElementsByClassName('header-title-one')[0])
  selectContent('baseShow')
  // var highShow = document.getElementById('highShow')
  // highShow.style.display = 'none'

  Ajax.get(CONSTANT.GET_BASE_URL, function (res) {
    console.log('获取基本信息： ', res)
    res = JSON.parse(res)
    var wlanName = document.getElementById('wlanName')
    var model = document.getElementById('model')
    var password = document.getElementById('password')
    var select = document.getElementById('select')
    wlanName.value = res.ssid
    for (i = 0; i < model.length; i ++) {
      if (res.auth_mode === model.options[i].value) {
        model.options[i].selected = true
      }
    }
    password.value = res.password
    select.checked = res.if_hide_ssid === 'true'
  })
  Ajax.get(CONSTANT.GET_HIGH_URL, function (res) {
    console.log('获取高级信息', res)
    res = JSON.parse(res)
    var broadband = document.getElementById('broadband')
    var channel = document.getElementById('channel')

    for (i = 0; i < broadband.length; i ++) {
      if (res.bandwidth === broadband.options[i].value) {
        broadband.options[i].selected = true
      }
    }
    for (i = 0; i < channel.length; i ++) {
      if (res.channel === channel.options[i].value) {
        channel.options[i].selected = true
      }
    }
  })

  getData();
  initShowList();
}
